import { Events } from '@tarojs/taro'

const getEventIns = function() {
  let result = null
  function _getEvent() {
    if(!result) {
      result = new Events()
    }
    return result
  }

  return _getEvent()
}

const eventInstance = getEventIns()
const EVENT_NAME = 'custom-message-box'

export const TYPES = ['confirm']
export const DEFAULT_TYPE = TYPES[0]

export const MessageBoxUtil = {
  show(args) {
    eventInstance.trigger(EVENT_NAME, {...args, show: true})
  },
  hide() {
    eventInstance.trigger(EVENT_NAME, { show: false })
  },
  getEventName() {
    return EVENT_NAME
  },
  /**
   *
   * @param { 回调函数 } callback
   * @param { this } thisArg
   */
  listen(callback, thisArg) {
    eventInstance.on(EVENT_NAME, callback, thisArg)
  },
  remove() {
    eventInstance.off(EVENT_NAME)
  }
}

TYPES.forEach(type => {
  /*
    option = {
      title: '标题123',
      content: '内容123'
    }
    option 可选项
    option.title 确认框的标题
    option.info 确认框的内容
    confirmCallback 确定按钮回调函数
    cancelCallback 取消按钮的回调函数
   */
  MessageBoxUtil[type] = (option, confirmCallback, cancelCallback) => {
    MessageBoxUtil.show.call(MessageBoxUtil, { ...option, type, confirmCallback, cancelCallback })
  }
})